﻿using GameDevClicker.GameEvents;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace GameDevClicker.Screens {
    /// <summary>
    /// The base for every screen used in the game.
    /// </summary>
    public abstract class BaseScreen : iEventListener {        
        private const float OVERLAYSPEED = 1f;
        private const float OVERLAYBREAKTIME = 0.3f;

        public string Name { get { return GetName(); } }
        private Image overlay;

        public abstract void Notify(string name, object args);
        public abstract IEnumerator OnScreenEnter();
        public abstract IEnumerator OnScreenExit();
        protected abstract string GetName();

        public BaseScreen() {
            GameEventSystem.Listen(this);
            overlay = GameObject.Find("r_Overlay").GetComponent<Image>();
        }

        ~BaseScreen() {
            GameEventSystem.Remove(this);
        }
        
        public virtual void Update(){}

        /// <summary>
        /// Function that allows to switch to a new screen.
        /// </summary>
        protected void SwitchToScreen(BaseScreen screen) {
            Main.Instance.SetScreen(screen);
        }

        protected IEnumerator Overlay(Color color) {
            color.a = 0;
            overlay.color = color;

            while (color.a < 1) {
                color.a += Time.deltaTime * OVERLAYSPEED;
                overlay.color = color;
                yield return null;
            }

            color.a = 1;
            yield return new WaitForSeconds(OVERLAYBREAKTIME);

            while (color.a > 0) {
                color.a -= Time.deltaTime * OVERLAYSPEED;
                overlay.color = color;
                yield return null;
            }

            color.a = 0;
            overlay.color = color;
        }
    }
}